import { app, shell, BrowserWindow, ipcMain, clipboard, nativeImage, dialog } from 'electron'
import { autoUpdater } from 'electron-updater'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import iconDrog from '../../resources/dropIcon.png?asset'
import icon from '../../resources/icon.png?asset'

const ncp = require('ncp').ncp;
const path = require('path');
const join = require('path').join;
const fs = require('fs');
const glob = require('glob'); // 遍历文件夹
const jschardet = require('jschardet');
const iconv = require('iconv-lite');

const tihuan = (config) => {
  return new Promise((resolve, rejects) => {
    // 要搜索的文件夹路径
    const folderPath = config.path + '/**/*';
    // 要搜索的文件扩展名
    const fileExtension = '.txt';
    // 要搜索的文本内容
    const searchText = config.v1;
    // 替换成的新文本内容
    const replaceText = config.v2;

    // 递归搜索文件夹中所有文本文件，并替换文本内容
    const files = glob.globSync(folderPath + fileExtension, {});
    files.forEach(function (file) {
      // 读取文件内容
      let data = fs.readFileSync(file);
      // 将文本内容进行替换

      const encoding = jschardet.detect(data).encoding;
      let content = ''
      
      if (encoding === 'GB2312' || encoding === 'KOI8-R') {
        content = iconv.decode(data, 'GBK');
      } else {
        content = data.toString()
      }
      fs.chmodSync(file, '700'); // 修改成全员读写权限
      // 将替换后的内容写回文件
      let newContent = content.replace(new RegExp(searchText, 'g'), replaceText);
      fs.writeFileSync(file, encoding === 'GB2312' ? iconv.encode(newContent, 'GBK') : newContent);
    });

    resolve(true)
  })
}

//所有窗体
let windows: {
  indexWindow: null | BrowserWindow,
} = {
  indexWindow: null, // 主窗口
}

const publicAtts = {
  width: 1200,
  height: 900,
  show: false,
  autoHideMenuBar: true,
  ...(process.platform === 'linux' ? { icon } : {}),
  webPreferences: {
    preload: join(__dirname, '../preload/index.js'),
    sandbox: false,
    nodeIntegration: true,
  }
}

function createIndexWindow(): void {
  // Create the browser window.node_modules
  windows.indexWindow = new BrowserWindow({
    ...publicAtts,
  })

  // ---启动将Mirserver-template模板复制进Mirserver,并将里面的-替换变量去掉---
  let downloadsFolder = ''
  if (!app.isPackaged) {
    downloadsFolder = process.cwd()
  } else {
    downloadsFolder = path.parse(app.getAppPath()).dir
  }
  let a = true
  ncp(path.join(downloadsFolder, 'Mirserver-template'), path.join(downloadsFolder, 'Mirserver'), (ncpErr) => {
    if (ncpErr) {
      return console.error('error1:', ncpErr);
    }
    if(a) {
      tihuan({
        path: path.join(downloadsFolder, 'Mirserver'),
        v1: '-替换变量',
        v2: '',
      })
      a = false
    }
  });
  // ---启动将Mirserver-template模板复制进Mirserver---

  windows.indexWindow.on('ready-to-show', () => {
    windows?.indexWindow?.show()
  })

  windows.indexWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    windows.indexWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    windows.indexWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

/** 接收渲染进程 操作窗口 的通知
 * @param {Object} event
 * @param {String} windowName 需要操作的窗口名称
 * @param {String} operationType 操作类型
 */
ipcMain.on('operation-window', function (event, operationType, other) {
  const focusedWindow = other?.windowName ? windows[other.windowName] :       BrowserWindow.getFocusedWindow();//当前操作的窗口实例
  if (!focusedWindow) return;
  switch (operationType) {
    case 'min'://窗口 最小化
      focusedWindow.minimize();
      break;

    case 'max'://窗口 最大化
      focusedWindow.maximize();
      break;

    case 'toggleMaximize'://窗口最大化或还原
      if (focusedWindow?.isMaximized()) {
        focusedWindow.unmaximize()
      } else {
        focusedWindow?.maximize()
      }
      break;

    case 'close'://窗口 关闭
      focusedWindow.close();
      break;

    case 'openDevTools'://打开控制台
      focusedWindow.webContents.openDevTools();
      break;

    case 'getDownloads'://获取下载目录
      event.returnValue = app.getPath('downloads')
      break;
      
    case 'getPathExe'://获取exe运行目录
      event.returnValue = path.dirname(app.getPath('exe'))
      break;
      
    case 'getAppPath'://获取项目目录
      event.returnValue = app.getAppPath()
      break;
      
    case 'isPackaged':// 项目是否打包，用于判断是否本地开发环境
      event.returnValue = app.isPackaged
      break;

    case 'startDragFile'://获取下载目录
      // const thumbnailFromPath = other.imgUrl ? nativeImage.createFromPath(iconDrog) : iconDrog;
      const thumbnailFromPath = nativeImage.createFromPath(iconDrog).resize({
        width: 30,
        height: 30,
      });
      event.sender.startDrag({
        file: other.file,
        icon: thumbnailFromPath
      })
      break;

    case 'copyToClipboard'://复制文本到剪贴板
      clipboard.writeText(other.text)
      break;

    case 'checkUpdate'://检测软件版本
      //检测更新
      autoUpdater.checkForUpdates()
      break;

    case 'updateDownloaded'://更新软件
      autoUpdater.downloadUpdate()
      break;

    case 'openPath'://打开文件夹
      shell.openPath(other.url);
      break;

    case 'selectDirectoryFile':
      dialog.showOpenDialog(focusedWindow, {
        title: '选择目录',
      }).then(result => {
        if (!result.canceled) {
          event.returnValue = result.filePaths[0]
        } else {
          event.returnValue = ''
        }
      }).catch(err => {
        console.error(err);
      });
      break;

    case 'selectDirectory':
      dialog.showOpenDialog(focusedWindow, {
        properties: ['openDirectory'],
        // defaultPath: 'C:\\',
        title: '选择目录',
      }).then(result => {
        if (!result.canceled) {
          event.returnValue = result.filePaths[0]
        } else {
          event.returnValue = ''
        }
      }).catch(err => {
        console.error(err);
      });
      break;
  }
});

ipcMain.handle('handle-window', function (event, operationType, other) {
  const focusedWindow = other?.windowName ? windows[other.windowName] : BrowserWindow.getFocusedWindow();//当前操作的窗口实例
  if (!focusedWindow) return;
  switch (operationType) {
    case 'isMaximized'://获取当前窗口是否最大化
      return focusedWindow?.isMaximized()

    case 'isMinimized'://获取当前窗口是否最小化
      return focusedWindow?.isMinimized()

    case 'getVersion'://获取app版本
      return app.getVersion()
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  // 默认 F12 在开发中打开或关闭 DevTools，在生产中忽略 CommandOrControl + R 。此外，您可以使用 shortcutOptions 来控制更多快捷方式
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createIndexWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createIndexWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  // if (process.platform !== 'darwin') {
  //   如果用户不是在 macOS(darwin) 上运行程序，则调用 app.quit()
  //   app.quit()
  // }
  app.quit()
})